<template>
  <div class="customer-detail-container">
    <el-card v-if="customerData" class="customer-detail-card" shadow="hover">
      <div class="customer-detail-content">
        <!-- 基本信息部分 -->
        <div class="info-section">
          <h3 class="section-title">基本信息</h3>
          <el-descriptions :column="2" size="large" class="info-descriptions">
            <el-descriptions-item label="客户名称">{{ customerData.name }}</el-descriptions-item>
            <el-descriptions-item label="客户类型">
              <el-tag :type="customerData.customer_type === 15 ? 'info' : 'primary'">
                {{
                  customerData.customer_type_name ||
                  (customerData.customer_type === 15 ? '个人' : '企业')
                }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="客户等级">
              {{ customerData.grade_name || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="会员状态">
              <template v-if="customerData.customer_status_name">
                <el-tag type="info">{{ customerData.customer_status_name }}</el-tag>
              </template>
              <template v-else>
                <el-tag type="info">未设置</el-tag>
              </template>
            </el-descriptions-item>
            <el-descriptions-item label="客户来源">
              {{ customerData.source_name || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="管家">
              {{ customerData.belong_name || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="客户分组代码">
              {{ customerData.group_code || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="是否主客户">
              <el-tag :type="customerData.is_primary === 1 ? 'success' : 'info'">
                {{ customerData.is_primary === 1 ? '是' : '否' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="负责人姓名">
              {{ customerData.controller_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="客户关系描述" :span="2">
              {{ customerData.relation_desc || '-' }}
            </el-descriptions-item>

            <!-- 联系信息组 -->
            <el-descriptions-item label="所在地区">
              {{ getRegionName(customerData) || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="详细地址" :span="2">
              {{ customerData.address || '未设置' }}
            </el-descriptions-item>

            <!-- 合同信息组 -->
            <el-descriptions-item label="合同数量">
              <span>
                {{ customerData.contract_num !== undefined ? customerData.contract_num : '0' }}
              </span>
            </el-descriptions-item>
            <el-descriptions-item label="合同总金额">
              <span>{{ formatAmount(customerData.contract_amount) }}</span>
            </el-descriptions-item>

            <!-- 其他信息组 -->
            <el-descriptions-item label="创建时间">
              {{ customerData.create_time || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="最新跟进时间">
              {{ customerData.follow_time || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="客户介绍" :span="2">
              {{ customerData.description || '未设置' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 会员信息卡片 -->
    <el-card v-if="customerData" class="customer-detail-card" shadow="hover">
      <div class="customer-detail-content">
        <!-- 会员信息部分 -->
        <div class="info-section">
          <h3 class="section-title">会员信息</h3>
          <el-descriptions :column="2" size="large" class="info-descriptions">
            <el-descriptions-item label="会员状态">
              <el-tag
                v-if="
                  customerData.customer_status !== undefined &&
                  statusService.isValidMemberStatus(customerData.customer_status)
                "
                type="success"
              >
                {{ customerData.customer_status_name || '会员(有效)' }}
              </el-tag>
              <el-tag
                v-else-if="
                  customerData.customer_status !== undefined &&
                  statusService.isExpiredMemberStatus(customerData.customer_status)
                "
                type="warning"
              >
                {{ customerData.customer_status_name || '过期会员' }}
              </el-tag>
              <el-tag v-else type="info">
                {{ customerData.customer_status_name || '非会员' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="客户属性">
              <el-tag v-if="customerData.customer_attribute === 3" type="primary">会员客户</el-tag>
              <el-tag v-else type="info">普通客户</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="会员类型">
              <span v-if="customerData.member_type === 1">普惠版</span>
              <span v-else-if="customerData.member_type === 2">标准版</span>
              <span v-else-if="customerData.member_type === 3">VIP版</span>
              <span v-else>未设置</span>
            </el-descriptions-item>
            <el-descriptions-item label="会员开始时间">
              {{ customerData.member_start_time || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="会员结束时间">
              {{ customerData.member_end_time || '未设置' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 子客户信息区块 - 仅主客户显示 -->
    <el-card
      v-if="customerData && customerData.is_primary === 1"
      class="customer-detail-card"
      shadow="hover"
    >
      <template #header>
        <div class="card-header">
          <span>子客户信息</span>
        </div>
      </template>
      <div class="sub-customer-section">
        <el-table
          v-loading="loading"
          :data="subCustomerList"
          border
          size="small"
          style="width: 100%"
        >
          <el-table-column prop="id" label="客户ID" width="80" align="center" />
          <el-table-column prop="name" label="客户名称" min-width="150">
            <template #default="{ row }">
              <a href="javascript:void(0)" @click="handleSubCustomerClick(row)">{{ row.name }}</a>
            </template>
          </el-table-column>
          <el-table-column prop="customer_type_name" label="客户类型" width="120" />
          <el-table-column prop="source_name" label="客户来源" width="120" />
          <el-table-column prop="grade_name" label="客户等级" width="100" />
          <el-table-column prop="belong_username" label="负责人" width="100" />
          <el-table-column prop="create_time" label="创建时间" width="160" />
        </el-table>
      </div>
    </el-card>

    <el-card v-if="customerData" class="customer-detail-card" shadow="hover">
      <div class="customer-detail-content">
        <!-- 开票信息部分 -->
        <div class="info-section">
          <h3 class="section-title">开票信息</h3>
          <el-descriptions :column="2" size="large" class="info-descriptions">
            <el-descriptions-item label="纳税人识别号">
              {{ customerData.tax_num || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="开户银行">
              {{ customerData.tax_bank || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="银行账号">
              {{ customerData.tax_banksn || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="财务电话">
              {{ customerData.tax_mobile || '未设置' }}
            </el-descriptions-item>
            <el-descriptions-item label="财务地址" :span="2">
              {{ customerData.tax_address || '未设置' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 标签页部分 -->
        <el-tabs
          v-model="activeTab"
          class="customer-detail-tabs"
          @tab-change="handleTabChangeWrapper"
        >
          <el-tab-pane label="联系人" name="contact">
            <div class="tab-content">
              <div class="tab-toolbar">
                <el-button type="primary" @click="handleAddContact">新增联系人</el-button>
              </div>
              <el-table :data="contactList" class="custom-table" border stripe>
                <el-table-column
                  prop="name"
                  label="姓名"
                  min-width="120"
                  align="left"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <div class="contact-name-cell">
                      <el-avatar :size="24" icon="UserFilled" class="avatar-icon"></el-avatar>
                      <span>{{ scope.row.name }}</span>
                      <el-tag
                        v-if="scope.row.is_default === 1"
                        type="success"
                        size="small"
                        effect="dark"
                        class="default-tag"
                      >
                        默认
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="mobile"
                  label="电话"
                  min-width="120"
                  align="center"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <el-link type="primary" :underline="false" v-if="scope.row.mobile">
                      <el-icon><Phone /></el-icon>
                      {{ scope.row.mobile }}
                    </el-link>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="email"
                  label="邮箱"
                  min-width="150"
                  align="center"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <el-link type="primary" :underline="false" v-if="scope.row.email">
                      <el-icon><Message /></el-icon>
                      {{ scope.row.email }}
                    </el-link>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="wechat"
                  label="微信"
                  min-width="120"
                  align="center"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <span v-if="scope.row.wechat">{{ scope.row.wechat }}</span>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right" align="center">
                  <template #default="scope">
                    <el-button
                      size="small"
                      type="warning"
                      plain
                      @click="handleEditContact(scope.row)"
                    >
                      编辑
                    </el-button>
                    <el-dropdown>
                      <el-button size="small" plain>
                        更多
                        <el-icon><arrow-down /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item
                            @click="handleSetDefault(scope.row)"
                            v-if="scope.row.is_default !== 1"
                          >
                            设为默认
                          </el-dropdown-item>
                          <el-dropdown-item @click="handleDeleteContactWrapper(scope.row)">
                            删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
              <div v-if="contactList.length === 0" class="empty-data">
                <el-empty description="暂无联系人数据" />
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="跟进记录" name="trace">
            <div class="tab-content">
              <div class="tab-toolbar">
                <el-button type="primary" @click="handleAddTrace">新增跟进</el-button>
              </div>
              <el-table :data="traceList" class="custom-table" border stripe>
                <el-table-column
                  prop="content"
                  label="跟进内容"
                  min-width="200"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <div class="trace-content-cell">
                      <el-icon><ChatLineRound /></el-icon>
                      <span class="text-ellipsis">{{ scope.row.content }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="admin_name"
                  label="跟进人"
                  width="120"
                  align="center"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="create_time"
                  label="跟进时间"
                  width="180"
                  align="center"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    {{ scope.row.create_time ? formatDateTime(scope.row.create_time) : '-' }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="next_time"
                  label="下次跟进"
                  width="180"
                  align="center"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <span>
                      {{ scope.row.next_time ? formatDateTime(scope.row.next_time) : '-' }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right" align="center">
                  <template #default="scope">
                    <el-button
                      size="small"
                      type="primary"
                      plain
                      @click="handleViewTrace(scope.row)"
                    >
                      查看
                    </el-button>
                    <el-dropdown
                      @command="(command: string) => handleTraceCommand(command, scope.row)"
                    >
                      <el-button size="small" plain>
                        更多
                        <el-icon><arrow-down /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item command="edit">编辑</el-dropdown-item>
                          <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
              <div v-if="traceList.length === 0" class="empty-data">
                <el-empty description="暂无跟进记录数据" />
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="销售机会" name="chance">
            <div class="tab-content">
              <div class="tab-toolbar">
                <el-button type="primary" @click="handleAddChance">新增机会</el-button>
              </div>
              <el-table :data="chanceList" class="custom-table">
                <el-table-column
                  prop="title"
                  label="机会名称"
                  min-width="150"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <span class="text-ellipsis">{{ scope.row.title }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="expected_order_amount" label="预计签单金额" width="120">
                  <template #default="scope">¥{{ scope.row.expected_order_amount }}</template>
                </el-table-column>
                <el-table-column prop="stage" label="阶段" width="120" show-overflow-tooltip>
                  <template #default="scope">
                    <el-tag v-if="scope.row.stage === 1" type="info">初步接触</el-tag>
                    <el-tag v-else-if="scope.row.stage === 2" type="info">需求分析</el-tag>
                    <el-tag v-else-if="scope.row.stage === 3" type="warning">方案报价</el-tag>
                    <el-tag v-else-if="scope.row.stage === 4" type="danger">商务谈判</el-tag>
                    <el-tag v-else-if="scope.row.stage === 5" type="success">成交</el-tag>
                    <el-tag v-else-if="scope.row.stage === 6" type="info">失败</el-tag>
                    <span v-else>未知</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="discovery_time"
                  label="发现时间"
                  width="180"
                  align="center"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    {{
                      scope.row.discovery_time
                        ? formatDateTime(scope.row.discovery_time * 1000)
                        : '-'
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="admin_name"
                  label="负责人"
                  width="120"
                  show-overflow-tooltip
                />
                <el-table-column label="操作" width="150" fixed="right">
                  <template #default="scope">
                    <el-button
                      size="small"
                      type="primary"
                      plain
                      @click="handleViewChance(scope.row)"
                    >
                      查看
                    </el-button>
                    <el-dropdown>
                      <el-button size="small" plain>
                        更多
                        <el-icon><arrow-down /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="handleEditChance(scope.row)">
                            编辑
                          </el-dropdown-item>
                          <el-dropdown-item @click="handleDeleteChance(scope.row)" divided>
                            删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
              <div v-if="chanceList.length === 0" class="empty-data">
                <el-empty description="暂无销售机会数据" />
              </div>
            </div>
          </el-tab-pane>

          <el-tab-pane label="操作日志" name="log">
            <div class="tab-content">
              <el-table :data="logList" class="custom-table">
                <el-table-column prop="field" label="操作字段" width="120" show-overflow-tooltip />
                <el-table-column prop="action" label="操作类型" width="120" show-overflow-tooltip />
                <el-table-column
                  prop="old_content"
                  label="原内容"
                  min-width="150"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <span class="text-ellipsis">{{ scope.row.old_content }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="new_content"
                  label="新内容"
                  min-width="150"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <span class="text-ellipsis">{{ scope.row.new_content }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="admin_name"
                  label="操作人"
                  width="120"
                  show-overflow-tooltip
                />
                <el-table-column
                  prop="create_time"
                  label="操作时间"
                  width="180"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    {{ scope.row.create_time ? formatDateTime(scope.row.create_time * 1000) : '-' }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>

    <!-- 联系人操作抽屉 -->
    <ContactDrawer
      v-model="contactDrawerVisible"
      :customer-id="
        customerData && customerData.id
          ? customerData.id
          : props.customerId
            ? Number(props.customerId)
            : route.params.id
              ? Number(route.params.id)
              : 0
      "
      :contact-id="currentContactId"
      :mode="contactOperationMode"
      :contact-data="getCurrentContactData()"
      @success="handleContactSuccess"
    />

    <!-- 跟进记录操作抽屉 -->
    <TraceDrawer
      v-model="traceDrawerVisible"
      :customer-id="
        customerData && customerData.id
          ? customerData.id
          : props.customerId
            ? Number(props.customerId)
            : route.params.id
              ? Number(route.params.id)
              : 0
      "
      :trace-id="currentTraceId"
      :mode="traceOperationMode"
      @success="handleTraceSuccess"
    />

    <!-- 销售机会操作抽屉 -->
    <ChanceDrawer
      v-model="chanceDrawerVisible"
      :customer-id="
        customerData && customerData.id
          ? customerData.id
          : props.customerId
            ? Number(props.customerId)
            : route.params.id
              ? Number(route.params.id)
              : 0
      "
      :chance-id="currentChanceId"
      :mode="chanceOperationMode"
      @success="handleChanceSuccess"
    />
  </div>
</template>

<script setup lang="ts">
  // 导入必要的库和组件
  import { onMounted, watch, computed } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { Phone, Message, UserFilled, ChatLineRound } from '@element-plus/icons-vue'
  import ContactDrawer from '@/components/business/customer/ContactDrawer.vue'
  import TraceDrawer from '@/components/business/customer/TraceDrawer.vue'
  import ChanceDrawer from '@/components/business/customer/ChanceDrawer.vue'
  import { formatDateTime } from '@/utils/format'
  import { statusService } from '@/utils/statusService'

  // 定义组件 props
  const props = defineProps<{
    customerId?: number | string
    isDrawer?: boolean
  }>()

  // 获取路由实例
  const route = useRoute()
  const router = useRouter()

  // 从外部文件导入所有逻辑
  import {
    customerData,
    activeTab,
    contactList,
    traceList,
    chanceList,
    logList,
    subCustomerList,
    loading,
    contactDrawerVisible,
    contactOperationMode,
    currentContactId,
    traceDrawerVisible,
    traceOperationMode,
    currentTraceId,
    chanceDrawerVisible,
    chanceOperationMode,
    currentChanceId,
    goBack,
    getRegionName,
    getChanceStageName,
    formatAmount,
    handleTabChange,
    loadCustomerDetail,
    loadContactList,
    loadTraceList,
    loadChanceList,
    loadLogList,
    handleAddContact,
    handleEditContact,
    handleDeleteContact,
    getCurrentContactData,
    handleContactSuccess,
    handleSetDefault,
    handleAddTrace,
    handleViewTrace,
    handleEditTrace,
    handleDeleteTrace,
    handleTraceCommand,
    handleTraceSuccess,
    handleAddChance,
    handleViewChance,
    handleEditChance,
    handleDeleteChance,
    handleChanceSuccess,
    handleSubCustomerClick,
    init,
  } from './CustomerDetailScript'

  // 计算当前客户ID
  const currentCustomerId = computed(() => {
    if (props.customerId) {
      return typeof props.customerId === 'string' ? Number(props.customerId) : props.customerId
    }
    return route.params.id ? Number(route.params.id) : 0
  })

  // 处理Tab切换
  const handleTabChangeWrapper = (tabName: string) => {
    // 使用props中的customerId或者路由参数
    const fakeRoute = props.customerId
      ? {
          params: {
            id: props.customerId,
          },
        }
      : route
    handleTabChange(tabName, fakeRoute)
  }

  // 删除联系人（需要传入route参数）
  const handleDeleteContactWrapper = (row: any) => {
    handleDeleteContact(row)
    // 重新加载联系人列表
    const customerId = props.customerId || (route.params.id as string)
    if (customerId) {
      loadContactList(parseInt(String(customerId)))
    }
  }

  // 统一监听客户ID变化 - 优化版本，减少重复请求
  watch(
    () => currentCustomerId.value,
    (newId, oldId) => {
      // 只有当ID真正发生变化时才触发，避免因为其他原因导致的重复请求
      if (newId && newId !== oldId) {
        init(newId)
      } else if (newId && !oldId) {
        // 初次加载时触发

        init(newId)
      }
    },
    {
      immediate: true,
      // 延迟执行，避免组件初始化时的重复触发
      flush: 'post',
    }
  )
</script>

<style scoped src="./CustomerDetailStyle.scss"></style>
